package com.lits.file.common;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class UploadUtil {
	private static final String DIR_SPLITOR = "/";
	private static final AppTypeEnum[] TYPE_VALUES = AppTypeEnum.values();
	public static final String TYPES_STR = getFileTypes();

	private static final Logger log = LoggerFactory.getLogger(UploadUtil.class);

	private UploadUtil() {
	}

	public static void closeStream(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				log.error("failed close stream");
			}
		}

	}

	public static String getFileType(String fileAbsPath) {
		int lastDotIndex = fileAbsPath.lastIndexOf('.');
		if (lastDotIndex == -1) {
			return "";
		} else {
			return fileAbsPath.substring(lastDotIndex);
		}
	}

	public static String getFileName(String fileAbsPath) {
		String path = fileAbsPath.replaceAll("[/\\\\]", DIR_SPLITOR);
		int lastDirSplitorIndex = path.lastIndexOf(DIR_SPLITOR);
		if (lastDirSplitorIndex == -1) {
			return "";
		} else {
			return fileAbsPath.substring(lastDirSplitorIndex + 1);
		}
	}

	public static boolean hasFile(MultipartFile f) {
		try {
			return f != null && f.getInputStream().available() > 0;
		} catch (IOException e) {
			// nothing
		}
		return false;
	}

	public static boolean rename(String srcAbsPath, String destName) {
		File srcf = new File(srcAbsPath);
		if (destName.indexOf('.') != -1) {
			return srcf.renameTo(new File(srcf.getParent() + DIR_SPLITOR + destName));
		}
		boolean res = srcf.renameTo(new File(srcf.getParent() + DIR_SPLITOR + destName + getFileType(srcAbsPath)));
		if (res && srcf.exists()) {
			res = srcf.delete();
		}
		return res;
	}

	public static boolean checkDirEnd(String path) {
		return StringUtils.isNotBlank(path) && !path.endsWith(DIR_SPLITOR);
	}

	public static String getFileTypes() {
		StringBuilder res = new StringBuilder();
		for (AppTypeEnum v : TYPE_VALUES) {
			res.append(v.name()).append(",");
		}
		return StringUtils.stripEnd(res.toString(), ",");
	}

	public static boolean checkType(String type) {
		for (AppTypeEnum v : TYPE_VALUES) {
			if (v.name().equals(type)) {
				return true;
			}
		}
		return false;
	}

	public static boolean checkWrongPath(String path) {
		return StringUtils.isBlank(path) || path.length() > 128 || path.matches(".*[:\\*\\?].*");
	}

	public static String joinFilePath(String... path) {
		if (path.length == 0) {
			return "";
		}
		StringBuilder bf = new StringBuilder();
		for (String p : path) {
			bf.append(StringUtils.removeEnd(StringUtils.removeEnd(p, "\\"), DIR_SPLITOR));
		}
		return bf.toString() + DIR_SPLITOR;
	}
}
